/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../utils/js.ts" />
/// <reference path="../log/log-manager.ts" />
/// <reference path="./worker.ts" />

namespace lcc {

const TAG = "lcc/worker/worker-group.ts";

/**
 * @zh
 * 工作者tick时间<br/>
 * 在[[Worker.onUpdate]]中使用的间隔时间
 */
export let WORKER_TICKTIME = 1;

/**
 * @zh
 * 工作组状态
 */
export enum GroupState {
    
    /**
     * @zh
     * 未初始化，表示group创建还未初始化
     */
    UNINITIALIZED,

    /**
     * @zh
     * 初始化中，表示group正在初始化
     */
    INITIALIZING,

    /**
     * @zh
     * 工作中，表示group初始化完成，正在工作中
     */
    WORKING,

    /**
     * @zh
     * 销毁中，表示group进入销毁释放阶段
     */
    DESTROYING,

    /**
     * @zh
     * 已销毁，表示worker已经销毁
     */
    DESTROYED,
}

/**
 * 优先worker标识符
 */
export interface PriorityWorkerIdentifier extends WorkerIdentifier {
    /**
     * 优先级
     */
    priority:number;
}

/**
 * @zh
 * 工作组
 */
export class WorkerGroup extends cocos.event.EventTarget {

    /**
     * 工作者优先级计数
     */
    private _workerPriCount:number = 0;

    /**
     * @zh
     * 工作组优先级
     */
    private _groupPriority:number = 0;

    /**
     * @zh
     * 工作组名称
     */
    private _groupName:string = null;

    /**
     * 工作者名称集合
     */
    protected _workerNameSet:{[key:string]:true} = null;

    /**
     * @zh
     * 工作者映射表
     */
    private _workerMap:{[key:string]:{[key:string]:WorkerBase}} = js.createMap();

	/**
     * @zh
	 * 是否使用心跳
	 */
	private _useHeart:boolean = false;

    /**
     * @zh
     * 工作组状态
     */
    private _state:GroupState = GroupState.UNINITIALIZED;

	/**
	 * @zh
	 * 构造工作组
	 */
	constructor(name:string, priority:number, workerNames:string[]){
		super();
		this._groupName = name;
		this._groupPriority = priority;
        this._workerNameSet = js.createSet(workerNames);
	}

	/**
	 * @zh
	 * 初始化工作组
	 */
    public async initialize(){
        this._setState(GroupState.INITIALIZING);
        this._setState(GroupState.WORKING);
	}
	
    /**
     * @zh
     * 获得工作者状态
     */
    public getState(){
        return this._state;
    }

    /**
     * @zh
     * 设置工作组状态
     * 
     * @param state 状态
     */
    public _setState(state:GroupState){
        if(state != this._state){
            this._state = state;
            this.emit(`__state-${state}`);
            this.emit(`__state`, state);
        }
    }
    
    /**
     * @zh
     * 直到工作组状态
     * 
     * @param state 状态
     */
    public async untilState(state:GroupState){
        return new Promise((resolve)=>{ 
            if(this._state == state){
                resolve(null);
            }else{
                this.once(`__state-${state}`, resolve); 
            }
        });
    }
    
	/**
     * @zh
	 * 安装心跳
	 */
	protected setupHeartTick(){
		if(!this._useHeart && !this.isGroupEmpty()){
			timerMgr.addTimer(WORKER_TICKTIME, this.onHeartTick.bind(this),{
                group : `lcc.WorkerGroup-${this._groupName}`, 
                key : "tick",
                loop : true
            });
			this._useHeart = true;
			DEBUG.WORKER && logMgr.debug(TAG, `setupHeartTick tick ${WORKER_TICKTIME}`);
		}
	}

    /**
     * @zh
     * 工作组为空
     */
    public isGroupEmpty(){
        for(let wName in this._workerMap){
            if(!js.isEmptyMap(this._workerMap[wName])){
                return false;
            }
        }
        return true;
    }

	/**
     * @zh
	 * 删除心跳
	 */
	protected deleteHeartTick(){
		if(this._useHeart && this.isGroupEmpty()){
			timerMgr.removeTimer({
                group : `lcc.WorkerGroup-${this._groupName}`, 
                key : "tick",
            });
			this._useHeart = false;
			DEBUG.WORKER && logMgr.debug(TAG, `deleteHeartTick tick`);
		}
	}
	
	/**
     * @zh
	 * 心跳回调
	 */
	private onHeartTick(dt:number){
        for(let wname of Object.keys(this._workerMap)){
            let instanceMap = this._workerMap[wname];
            if(instanceMap){
                for(let iname of Object.keys(instanceMap)){
                    let worker = instanceMap[iname];
                    if(worker && worker.isRunning()){
                        worker._update(dt);
                    }
                }
            }
        }
    }
    
    /**
     * @zh
     * 获得工作组优先级
     */
    public getPriority(){
        return this._groupPriority;
    }

    /**
     * @zh
     * 获得工作组名
     */
    public getName(){
        return this._groupName;
    }

    /**
     * @zh
     * 检测工作组是否包含工作者
     * 
     * @param workerName 
     */
    public containWorkerName(workerName:string){
        return this._workerNameSet[workerName];
    }
    
    /**
     * @zh
     * 启动工作者<br/>
     * **注意工作者和其配置应该是对应不变的，每个工作者都对应唯一配置**<br/>
     * 所以，多次创建同一名称工作者的配置应该一样。
     * 
     * @param workerMeta - 工作者元数据。
     */
    public async startWorker(workerMeta:WorkerMeta){
        if(this._state != GroupState.WORKING){
			logMgr.warn(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' group does not work`);
            return false;
        }
        let workerClass:typeof WorkerBase = requireWorkerClass(workerMeta.id.workerName);
        if(!workerClass){
            logMgr.warn(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' not found worker class`);
            return false;
        }
        DEBUG.WORKER && logMgr.debug(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' args:${workerMeta.args?JSON.stringify(workerMeta.args):'NULL'}`);
        
        workerMeta.id.instanceName = workerMeta.id.instanceName || DEFAULT_INSTANCE_NAME;
        workerMeta.args = workerMeta.args || [];
        let instanceMap = this._workerMap[workerMeta.id.workerName];
        if(!instanceMap){
            instanceMap = js.createMap();
            this._workerMap[workerMeta.id.workerName] = instanceMap;
            if(this._groupName == DEFAULT_WORKER_GROUP){
                this._workerNameSet[workerMeta.id.workerName] = true;
            }
        }
        let worker = instanceMap[workerMeta.id.instanceName];
        // 如果工作者存在
        if(worker){
            let wstate = worker.getState();
            switch(wstate){
                case WorkerState.STOPPED:{
                    break;
                }
                case WorkerState.STARTING:{
                    await worker.untilState(WorkerState.RUNNING);
                    DEBUG.WORKER && logMgr.debug(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' STARTING -> RUNNING`);
                    return true;
                }
                case WorkerState.RUNNING:{
                    DEBUG.WORKER && logMgr.debug(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' RUNNING`);
                    return true;
                }
                case WorkerState.SOFT_STOPPING:{
                    worker._setState(WorkerState.RUNNING);
                    DEBUG.WORKER && logMgr.debug(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' SOFT_STOPPING -> RUNNING`);
                    return true;
                }
                case WorkerState.STOPPING:{
                    await worker.untilState(WorkerState.STOPPED);
                    break;
                }
            }
        }

        // 创建新工作者
        worker = new workerClass(...(workerMeta.args));
        worker._setGroup(this);
        worker._setWorkerName(workerMeta.id.workerName);
        worker._setInstanceName(workerMeta.id.instanceName);
        worker.setPriority(++this._workerPriCount);
        instanceMap[workerMeta.id.instanceName] = worker;
        this.setupHeartTick();
        
        // 启动工作者
        worker._setState(WorkerState.STARTING);
        await worker.onStart();
        worker._setState(WorkerState.RUNNING);
        DEBUG.WORKER && logMgr.debug(TAG, `startWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' success`);
        return true;
    }

    /**
     * @zh
     * 停止工作者
     * 
     * @param workerIDorMeta - 工作者标识或者工作者元数据。如果为字符串，则表示工作者名称，所属工作组默认为当前工作组
     * @param soft - 软停止
     */
    public async stopWorker(workerIDorMeta:string|WorkerIdentifier|WorkerMeta, soft:boolean = false){
        let workerMeta = optionWorkerMeta(workerIDorMeta);
        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}'`);

        workerMeta.id.instanceName = workerMeta.id.instanceName || DEFAULT_INSTANCE_NAME;
		let instanceMap = this._workerMap[workerMeta.id.workerName];
        if(instanceMap){
            let worker = instanceMap[workerMeta.id.instanceName];
            if(worker){
                let wstate = worker.getState();
                switch(wstate){
                    case WorkerState.STOPPED:{
                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' STOPPED`);
                        return true;
                    }
                    case WorkerState.STARTING:{
                        await worker.untilState(WorkerState.RUNNING);
                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' untilState RUNNING`);
                        break;
                    }
                    case WorkerState.RUNNING:{
                        break;
                    }
                    case WorkerState.SOFT_STOPPING:{
                        if(soft){
                            return new Promise<boolean>((resolve)=>{ 
                                let stateChange = (state:WorkerState)=>{
                                    if(state == WorkerState.RUNNING){
                                        worker.off(`__state`, stateChange);
                                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' SOFT_STOPPING -> RUNNING`);
                                        resolve(false);
                                    }else if(state == WorkerState.STOPPED){
                                        worker.off(`__state`, stateChange);
                                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' SOFT_STOPPING -> STOPPED`);
                                        resolve(true);
                                    }
                                };
                                worker.on(`__state`, stateChange); 
                            });
                        }else{
                            worker._setState(WorkerState.STOPPING);
                            await worker.untilState(WorkerState.STOPPED);
                            DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' STOPPING -> STOPPED`);
                            return true;
                        }
                    }
                    case WorkerState.STOPPING:{
                        await worker.untilState(WorkerState.STOPPED);
                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' STOPPING -> STOPPED`);
                        return true;
                    }
                }
    
                if(soft && worker.getWorks() > 0){
                    worker._setState(WorkerState.SOFT_STOPPING);
                    return new Promise<boolean>((resolve)=>{
                        let stateRuning = ()=>{
                            worker.off(`__state-${WorkerState.RUNNING}`, stateRuning);
                            worker.off(`__STOPPING`, doingStop);
                            DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' failure`);
                            resolve(false);
                        };
                        let doingStop = async ()=>{
                            worker.off(`__state-${WorkerState.RUNNING}`, stateRuning);
                            worker.off(`__STOPPING`, doingStop);
                            await worker.onStop();
                            worker._setState(WorkerState.STOPPED);
                            delete instanceMap[workerMeta.id.instanceName];
                            this.deleteHeartTick();
                            DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' success`);
                            resolve(true);
                        };
                        worker.on(`__state-${WorkerState.RUNNING}`, stateRuning);
                        worker.on(`__STOPPING`, doingStop);
                    });
                }else{
                    worker._setState(WorkerState.STOPPING);
                    if(worker.getWorks() > 0){
                        return new Promise<boolean>((resolve)=>{
                            worker.once(`__STOPPING`, async ()=>{
                                await worker.onStop();
                                worker._setState(WorkerState.STOPPED);
                                delete instanceMap[workerMeta.id.instanceName];
                                this.deleteHeartTick();
                                DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' success`);
                                resolve(true);
                            });
                        });
                    }else{
                        await worker.onStop();
                        worker._setState(WorkerState.STOPPED);
                        delete instanceMap[workerMeta.id.instanceName];
                        this.deleteHeartTick();
                        DEBUG.WORKER && logMgr.debug(TAG, `stopWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' success`);
                        return true;
                    }
                }
            }
        }
    }

    /**
     * @zh
     * 调用工作者
     * 
     * @param workerIDorMeta - 工作者标识或者工作者元数据。如果为字符串，则表示工作者名称，所属工作组默认为当前工作组
     * @param type - 调用类型
     * @param args - 调用参数
     */
    public async callWorker(workerIDorMeta:string|WorkerIdentifier|WorkerMeta, type:string, ...args:any[]):Promise<WorkerCallResult>{
        let workerMeta = optionWorkerMeta(workerIDorMeta);
        if(this._state != GroupState.WORKING){
			logMgr.warn(TAG, `callWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' group does not work`);
            return {
                error : WorkerCallError.GROUP_NOT_WORK
            }
        }
        DEBUG.WORKER && logMgr.debug(TAG, `callWorker '${this._groupName}-${workerMeta.id.workerName}-${workerMeta.id.instanceName}' ${type}`);
        
        workerMeta.id.instanceName = workerMeta.id.instanceName || DEFAULT_INSTANCE_NAME;
        if(workerMeta.args){
            await this.startWorker(workerMeta);
        }
        let instanceMap = this._workerMap[workerMeta.id.workerName];
        if(!instanceMap){
            return {
                error : WorkerCallError.WORKER_NOT_FOUND
            }
        }
        let worker = instanceMap[workerMeta.id.instanceName];
        let wstate = worker.getState();
        if(wstate == WorkerState.SOFT_STOPPING){
            worker._setState(WorkerState.RUNNING);
        }
        if(!worker.isCallable()){
            return {
                error : WorkerCallError.WORKER_NOT_CALLABLE
            }
        }
        let callFun = worker[type];
        if(!callFun){
            return {
                error : WorkerCallError.FUNCTION_NOT_FOUND
            }
        }
        if(!worker.isRunning()){
            return {
                error : WorkerCallError.WORKER_NOT_RUNNING
            }
        }

        // 调用函数
        worker._addWork();
        try{
            this.emit('__onWorkCall');
            let result = await callFun.call(worker, ...args);
            worker._decWork();
            return {
                return : result,
            }
        }catch(e){
            worker._decWork();
            return {
                error : WorkerCallError.CALL_EXCEPTION
            }
        }
    }

    /**
     * @zh
     * 通知所有工作者
     * 
     * @param type 调用类型
     * @param args 调用参数
     */
    public async notifyAll(type:string, ...args:any[]){
        if(this._state != GroupState.WORKING){
			return logMgr.warn(TAG, `notifyAll '${this._groupName}' group does not work`);
        }
        DEBUG.WORKER && logMgr.debug(TAG, `notifyAll '${this._groupName}' ${type}`);
        
        for(let workerID of Object.keys(this._workerMap)){
            await this.callWorker(workerID, type, ...args);
        }
    }
    
    /**
     * @zh
     * 销毁工作组
     */
    public async destroy(){
        DEBUG.WORKER && logMgr.debug(TAG, `destroy '${this._groupName}'`);
        this._setState(GroupState.DESTROYING);
        let pWorkerIDs:PriorityWorkerIdentifier[] = [];
        for(let wName in this._workerMap){
            let iMap = this._workerMap[wName];
            for(let iName in iMap){
                let worker = iMap[iName];
                pWorkerIDs.push({
                    workerName : worker.getWorkerName(),
                    instanceName : worker.getInstanceName(),
                    priority : worker.getPriority(),
                });
            }
        }
        pWorkerIDs.sort((a,b)=>{ return b.priority - a.priority; });
        for (let pWorkerID of pWorkerIDs){
            await this.stopWorker(pWorkerID);
        }
        this._setState(GroupState.DESTROYED);
    }
}

}    
